package com.hy.hywebview.webviewprocess;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.hy.hywebview.bean.JsParam;
import com.hy.hywebview.webviewprocess.settings.WebViewDefaultSettings;
import com.hy.hywebview.webviewprocess.webchromeclient.HYWebChromeClient;
import com.hy.hywebview.webviewprocess.webviewclient.HYWebViewClient;
import com.hy.hywebview.webviewprocess.webviewclient.WebViewCallBack;

/**
 * @Description:自定义WebView
 * @Author: wdk
 * @CreateTime: 2024/4/13 17:41
 */
public class HYWebView extends WebView {
    private static final String TAG = "HYWebView";

    public HYWebView(@NonNull Context context) {
        super(context);
        init();
    }

    public HYWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HYWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public HYWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        //绑定主进程
        WebViewProcessCommandsDispatcher.INSTANCE.initAidlConnection();
        //注入对象到 js window
        addJavascriptInterface(this,"hywebview");
        //进行webview的默认设置
        WebViewDefaultSettings.getInstance().setSettings(this);
    }

    public void registerWebViewCallback(WebViewCallBack webViewCallBack) {
        setWebViewClient(new HYWebViewClient(webViewCallBack));
        setWebChromeClient(new HYWebChromeClient(webViewCallBack));
    }

    @JavascriptInterface
    public void takeNativeAction(String jsParam){
        Log.e(TAG, "this is a call from html javascript." + jsParam);
        if (!TextUtils.isEmpty(jsParam)) {
            final JsParam jsParamObject = new Gson().fromJson(jsParam, JsParam.class);
            if (jsParamObject != null) {
                WebViewProcessCommandsDispatcher.INSTANCE.executeCommand(jsParamObject.name, new Gson().toJson(jsParamObject.param), this);
            }
        }
    }

    public void handleCallback(final String callbackname, final String response){
        if(!TextUtils.isEmpty(callbackname) && !TextUtils.isEmpty(response)){
            post(new Runnable() {
                @Override
                public void run() {
                    String jscode = "javascript:hyjs.callback('" + callbackname + "'," + response + ")";
                    evaluateJavascript(jscode, null);
                }
            });
        }
    }
}
